package com.yhsoft.flim.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsoft.common.service.FuSiLingFlimApiService;
import com.yhsoft.flim.controller.po.JsonData;
import com.yhsoft.flim.controller.request.GetCinemaInVo;
import com.yhsoft.flim.controller.response.CinemaOutVo;
import com.yhsoft.flim.entity.Cinema;
import com.yhsoft.flim.mapper.CinemaMapper;
import com.yhsoft.flim.service.ICinemaService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 电影院信息 服务实现类
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-12-05
 */
@Service
public class CinemaServiceImpl extends ServiceImpl<CinemaMapper, Cinema> implements ICinemaService {

    @Override
    public void synJob() throws IOException {
        String msg = FuSiLingFlimApiService.cinemaList();
        System.out.println("response >>> : " + msg);

        JsonData cinemaData = JSON.parseObject(msg, JsonData.class);
        List<Cinema> cinemas = JSON.parseArray(cinemaData.getData().toString(), Cinema.class);
        cinemas.forEach((cinema) -> {
            System.out.println(cinema.getId());
            System.out.println(cinema.getCinemaName());
            System.out.println(cinema.getCityName());
            System.out.println(cinema.getAddress());
            cinema.setUpdatedTime(LocalDateTime.now());
            cinema.setDeleted(0);
        });
        this.saveOrUpdateBatch(cinemas);

    }

    @Override
    public IPage<CinemaOutVo> getCinema(GetCinemaInVo inVo, Long pageNo, Long pageSize) throws IOException {
        boolean a = this.getBaseMapper().exists(new QueryWrapper<Cinema>());
        if (!a) {
            // 未查询到电影院数据的话，执行调用接口
            this.synJob();
        }

        QueryWrapper<CinemaOutVo> wrapper = new QueryWrapper<>();
        wrapper.likeRight(inVo.getCityCode() != null, "city_code", inVo.getCityCode());

        Page<CinemaOutVo> page = new Page<>(pageNo, pageSize);
        IPage<CinemaOutVo> iPage = this.getBaseMapper().selectCinemaPage(page, wrapper, inVo.getLongitude(), inVo.getLatitude());

        return iPage;
    }
}
